const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const OrderItem = sequelize.define('OrderItem', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    orderId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'orders',
            key: 'id'
        }
    },
    productId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'products',
            key: 'id'
        }
    },
    productName: {
        type: DataTypes.STRING(200),
        allowNull: false
    },
    productSku: {
        type: DataTypes.STRING(100),
        allowNull: false
    },
    productImage: {
        type: DataTypes.STRING(255),
        allowNull: true
    },
    quantity: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
            min: {
                args: 1,
                msg: '数量必须大于0'
            }
        }
    },
    unitPrice: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        validate: {
            min: {
                args: 0,
                msg: '单价不能为负数'
            }
        }
    },
    totalPrice: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        validate: {
            min: {
                args: 0,
                msg: '总价不能为负数'
            }
        }
    }
}, {
    tableName: 'order_items',
    timestamps: true,
    indexes: [
        {
            fields: ['orderId']
        },
        {
            fields: ['productId']
        }
    ]
});

module.exports = OrderItem;